package com.hsd.whb.security;

import com.hsd.whb.entity.Recorder;
import com.hsd.whb.repository.RecorderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class HwbRecorderUserDetailsService implements UserDetailsService {

    private RecorderRepository recorderRepository;

    public HwbRecorderUserDetailsService(RecorderRepository recorderRepository) {
        this.recorderRepository = recorderRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Recorder recorder = recorderRepository.findByUsername(username);
        if (recorder != null) {
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_RECORDER"));
            boolean deleted = recorder.getDeleted() == 0 ? true : false;
            return new User(username, recorder.getPassword(), deleted, true, true, true, authorities);
        }
        throw new UsernameNotFoundException("用户名不存在");
    }


}
